﻿using System;
using Microsoft.WindowsAzure.StorageClient;
using System.Data.Services.Client;

namespace Caramel.WindowsAzure
{
	public class TableStorageUnitOfWork : IUnitOfWork
	{
		private bool _isDisposed = false;

		public TableStorageUnitOfWork(TableServiceContext context, string name)
		{
			this.Context = context;
			this.Name = name;
			this.ID = Guid.NewGuid();
		}

		public TableServiceContext Context { get; set; }

		public string Name { get; private set; }

		public Guid ID { get; private set; }

		public bool WasCommitted { get; private set; }

		public bool WasRolledBack { get; private set; }

		public void Commit()
		{
			this.Context.SaveChanges();
			this.WasCommitted = true;
		}

		public void Rollback()
		{
			this.WasRolledBack = true;
		}

		public void Evict(object entity)
		{
			this.Context.Detach(entity);
		}

		public void Dispose()
		{
			if (!_isDisposed)
			{
				UnitOfWork.DisposeOfUnitOfWork(this);

				_isDisposed = true;
			}
		}
	}
}
